package elasticsearch

import (
	"center-data-platform/utils/elasticsearch/internal/config"
	"fmt"
	"github.com/elastic/go-elasticsearch/v8"
	"github.com/elastic/go-elasticsearch/v8/esapi"
	"github.com/zeromicro/go-zero/core/conf"
	"path/filepath"
	"runtime"
	"strings"
)

type ESClient struct {
	Client *elasticsearch.Client
}

func NewClient() *ESClient {
	var c config.Config
	_, filename, _, ok := runtime.Caller(0)
	if !ok {
		panic("es init error : No caller information")
	}
	dir := filepath.Dir(filename)
	path := filepath.Join(dir, "etc", "es.yaml")
	conf.MustLoad(path, &c)
	fmt.Println(c)
	client, err := elasticsearch.NewClient(elasticsearch.Config{
		Addresses: c.Addresses,
		Username:  c.Username,
		Password:  c.Password,
	})
	if err != nil {
		panic(err)
	}
	return &ESClient{Client: client}
}

func (e *ESClient) Search(index string, query string) (*esapi.Response, error) {
	res, err := e.Client.Search(e.Client.Search.WithIndex(index), e.Client.Search.WithBody(strings.NewReader(query)))
	if err != nil {
		return nil, err
	}
	result := res
	return result, nil
}

func (e *ESClient) CreateDoc(index string, query string) (*esapi.Response, error) {
	res, err := e.Client.Index(
		index,
		strings.NewReader(query),
	)
	if err != nil {
		return nil, err
	}
	//defer res.Body.Close()
	return res, nil
}
